<template>
  <div>
    <ListTab v-if="!showMobilePage" show-header is-table />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page question-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          is-show-config
          show-search-btn
          @selectChange="handelFilterInputChange"
          @deleteTagBefore="deleteTagBefore"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <createBtn v-if="hasRouteAuth('crm:question:create')" style="margin-right: 10px;" @click.native="handleCreate"/>
        <MoreOpeator
          v-if="hasRouteAuth('crm:question:create') || hasRouteAuth('crm:question:delete')"
          ref="moreOpeatorRef"
          :list="moreOperatorList"
        />
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list.items.length"
            ref="questionTableRef"
            :data="list.items"
            :border="true"
            :row-height="rowHeight(54)"
            :height="setTableHeight"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table question-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @sort-change="sortMethod"
            @select="selectTable"
            @select-all="selectTable">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column :min-width="handleTdWidth()" align="left" label="问题编号" width="150">
              <template slot-scope="scope">
                <div v-if="scope.row.sn" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                  <ToolTip :content="handleSnNumber(scope.row.sn)" is-can-click @handelClick="toDetail(scope.row)" />
                </div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="问题名称" sortable="custom" prop="content" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.content" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="问题类型" sortable="custom" prop="type" min-width="100">
              <template slot-scope="scope">
                <div :class="`question-type type${scope.row.type}`">{{ formatQuestionType(scope.row.type) }}</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="回答次数" sortable="custom" prop="number" min-width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.number || '--' }}</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号属性">
              <template slot-scope="scope">
                <div>{{ scope.row.attribute ? '是' : '否' }}</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="更新人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.updater" :label="scope.row.updater" :user-id="scope.row.updaterId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="flex-center">
                  <div v-if="!showMobilePage" class="button-text" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {label: '查看', handelClick: () => {toDetail(scope.row)}, auth: showMobilePage},
                      {label: '编辑', handelClick: () => {handleEdit(scope.row)}, disabled: !hasRouteAuth('crm:question:create')},
                      {label: '删除', handelClick: () => {handleDelete(0, scope.row.id)}, disabled: !hasRouteAuth('crm:question:delete')},
                  ]">
                    <div v-if="!showMobilePage" slot="button" class="button-text border-left">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination>
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @selectChange="handelFilterInputChange"
              @deleteTagBefore="deleteTagBefore"
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              v-if="hasRouteAuth('crm:question:create') || hasRouteAuth('crm:question:delete')"
              ref="moreOpeatorRef"
              :list="moreOperatorList"
              show-mobile-icon
            />
            <createBtn v-if="hasRouteAuth('crm:question:create')" mobile-table @click.native="handleCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
      <addDialog ref="addQuestionRef" @updateData="fetchData" @searchSameQuestion="searchSameQuestion"/>
      <mergeDialog ref="mergeRef" @updateData="updateData"/>
    </div>
  </div>
</template>

<script>
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ListTab from '@/components/ListTab';
import mergeDialog from './components/mergeDialog.vue';
import addDialog from './components/addDialog.vue';
import { deleteQuestion, getQuestionDetail, getQuestionList } from '@/api/question';
import { formatQuestionType } from '@/filters/status';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import tableSelections from '@/mixins/tableSelections';
import ElMessage, { showModal } from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import { generateUUID } from '@/utils/tools';
import { mapState } from 'vuex';

export default {
  components: { ListTab, EmptyPlaceholder, createBtn, MoreOpeator, addDialog, mergeDialog },
  mixins: [TableAdaptive, mobileTable, tableSelections],
  data() {
    return {
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      sortName: '',
      sortType: '',
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      typeList: [
        { label: '问答题', value: 0 },
        { label: '是非题', value: 1 },
        { label: '多选题', value: 2 },
        { label: '单选题', value: 3 },
        { label: '仅描述', value: 4 },
        { label: '图片题', value: 5 }
      ],
      isUmyTable: true,
      tableRefName: 'questionTableRef', // 表格的ref名称
      idKey: 'id' // 唯一表示字段
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      const arr = [
        { keyword: 'content', name: '问题名称', labelWidth: '100px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'updater', name: '更新人', labelWidth: '100px', type: 'input' },
        { keyword: 'type', name: '问题类型', type: 'select', options: this.typeList },
        { keyword: 'attribute', name: '账号属性', type: 'select', options: [{ label: '是', value: 1 }, { label: '否', value: 0 }] }
      ];
      return arr;
    },
    moreOperatorList() {
      return [
        { label: '合并', handelClick: this.handleMerge, auth: hasRouteAuth('crm:question:merge') },
        { label: '批量删除', handelClick: this.handleDelete, auth: hasRouteAuth('crm:question:delete') }
      ];
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'questionDetail') {
      to.meta.isRedirectCreate = true;
    } else {
      to.meta.isRedirectCreate = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isRedirectCreate) {
      this.fetchData();
    } else {
      const { content, type } = this.$route.query;
      if (content && type) {
        this.searchSameQuestion({ content, type: Number(type) });
      }
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    }
  },
  methods: {
    hasRouteAuth,
    formatQuestionType,
    deleteTagBefore(key) {
      if (key === 'platformId') {
        this.$set(this.paramsObj, 'cooperationFormId', '');
      }
    },
    handelFilterInputChange({ value, item }) {
      if (item.keyword === 'platformId') {
        this.$set(this.paramsObj, 'cooperationFormId', '');
      }
    },
    handleMerge() {
      let msg = '';
      if (this.multipleSelectionAll.length === 0) {
        msg = '请先选择问题';
      } else if (this.multipleSelectionAll.length === 1) {
        msg = '请至少选择2个问题';
      } else if (this.multipleSelectionAll.length > 20) {
        msg = '不可一次性合并超过20个问题';
      }
      if (msg) {
        ElMessage.warning(msg);
        return;
      }
      // 判断问题类型是否一样
      const temp = this.multipleSelectionAll.map(item => item.type);
      const res = temp.some(ele => {
        return ele !== temp[0];
      });
      if (res) {
        ElMessage.warning('问题类型不一致，无法合并');
        return;
      }
      this.$refs.mergeRef.initData(this.multipleSelectionAll);
    },
    updateData() {
      this.clearMixinSelection();
      this.fetchData();
    },
    handleDelete(isBatchDelete = 1, id = '') {
      if (isBatchDelete && this.multipleSelectionAll.length === 0) {
        ElMessage.warning('请先选择问题');
        return;
      }
      const ids = !isBatchDelete ? id : (this.multipleSelectionAll.map(item => item.id).join());
      showModal('请确认是否删除?').then(_ => {
        deleteQuestion({ ids }).then(_ => {
          const temp = isBatchDelete ? this.multipleSelectionAll.length : 1;
          if (this.page > 1 && this.perPage * (this.page - 1) + temp === this.list.total) {
            this.page--;
          }
          if (isBatchDelete) {
            this.clearMixinSelection();
          } else {
            this.resetItemSelected(id);
          }
          this.$message.success('删除成功');
          this.fetchData();
        });
      });
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData();
    },
    formatParams() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      return paramsObj;
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      params.page = this.page;
      params.perPage = this.perPage;
      getQuestionList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        this.list.isInit = false;
        console.log(err);
      });
    },
    searchSameQuestion(params) {
      this.paramsObj = {
        content: params.content,
        type: params.type
      };
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handleCreate() {
      this.$refs.addQuestionRef.initData();
    },
    async handleEdit(row) {
      const res = await getQuestionDetail(row.id);
      if (res.code === 200) {
        const data = {
          id: row.id,
          attribute: res.data.attribute,
          _uuid: generateUUID(),
          remarks: [{
            type: res.data.type,
            content: res.data.content,
            selectList: res.data.selectList
          }]
        };
        if ([2, 3].includes(data.remarks[0].type)) {
          data.remarks[0].selectList.forEach(item => {
            item._uuid = generateUUID();
          });
        }
        this.$refs.addQuestionRef.initData(0, data);
      }
    },
    toDetail(row) {
      this.$router.push({
        name: 'questionDetail',
        params: { id: row.id }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/views/question/question.scss";
.question-list{
	margin: 16px 16px 0 16px;
	background-color: #fff;
	padding: 20px 24px 55px 24px;
}
.border-left {
  position: relative;
  padding-left:6px;
  margin-left: 6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.filter {
	display: flex;
	align-items: center;
  margin-bottom: 16px;
}
</style>
